<template>
  <div class="date-picker">
    <div class="picker-trigger" @click="toggleDropdown">
      <div class="selected-content">
        <Calendar :size="16" class="trigger-icon" />
        <span class="selected-text">{{ displayText }}</span>
      </div>
      <ChevronDown :size="16" class="chevron" :class="{ rotated: isOpen }" />
    </div>

    <div v-if="isOpen" class="dropdown-overlay" @click="closeDropdown"></div>

    <div v-if="isOpen" class="dropdown-content">
      <div class="date-controls">
        <div class="date-input-group">
          <label class="date-label">开始日期</label>
          <input v-model="startDate" type="date" class="date-input" @change="handleDateChange" />
        </div>

        <div class="date-input-group">
          <label class="date-label">结束日期</label>
          <input v-model="endDate" type="date" class="date-input" @change="handleDateChange" />
        </div>
      </div>

      <div class="quick-actions">
        <button
          v-for="action in quickActions"
          :key="action.value"
          class="quick-action-btn"
          :class="{ active: isQuickActionActive(action.value) }"
          @click="applyQuickAction(action.value)"
        >
          {{ action.label }}
        </button>
      </div>

      <div class="date-actions">
        <button class="clear-btn" @click="clearDates">清除</button>
        <button class="apply-btn" @click="applyDates">应用</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Calendar, ChevronDown } from 'lucide-vue-next'

interface DateRange {
  startDate: string
  endDate: string
}

interface Props {
  modelValue?: DateRange | null
}

interface Emits {
  (e: 'update:modelValue', value: DateRange | null): void
  (e: 'change', value: DateRange | null): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: null
})

const emit = defineEmits<Emits>()

// 从props初始化日期，如果提供了modelValue
const initDatesFromProps = () => {
  if (props.modelValue) {
    startDate.value = props.modelValue.startDate
    endDate.value = props.modelValue.endDate
  }
}

// 为了方便测试，自动选择一个默认日期范围
onMounted(() => {
  // 如果没有提供初始值，默认选择"最近30天"
  if (!props.modelValue) {
    applyQuickAction('last30Days')
    applyDates()
  } else {
    initDatesFromProps()
  }
})

const startDate = ref('')
const endDate = ref('')
const isOpen = ref(false)

const quickActions = [
  { label: '今天', value: 'today' },
  { label: '昨天', value: 'yesterday' },
  { label: '本周', value: 'thisWeek' },
  { label: '本月', value: 'thisMonth' },
  { label: '最近7天', value: 'last7Days' },
  { label: '最近30天', value: 'last30Days' }
]

const displayText = computed(() => {
  if (!startDate.value && !endDate.value) {
    return '选择日期范围'
  }

  if (startDate.value && endDate.value) {
    if (startDate.value === endDate.value) {
      return formatDisplayDate(startDate.value)
    }
    return `${formatDisplayDate(startDate.value)} - ${formatDisplayDate(endDate.value)}`
  }

  if (startDate.value) {
    return `从 ${formatDisplayDate(startDate.value)}`
  }

  if (endDate.value) {
    return `到 ${formatDisplayDate(endDate.value)}`
  }

  return '选择日期范围'
})

const formatDisplayDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

const formatDate = (date: Date): string => {
  return date.toISOString().split('T')[0]
}

const getToday = (): Date => new Date()
const getYesterday = (): Date => {
  const date = new Date()
  date.setDate(date.getDate() - 1)
  return date
}

const getThisWeek = (): { start: Date; end: Date } => {
  const today = new Date()
  const start = new Date(today)
  start.setDate(today.getDate() - today.getDay())
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  return { start, end }
}

const getThisMonth = (): { start: Date; end: Date } => {
  const today = new Date()
  const start = new Date(today.getFullYear(), today.getMonth(), 1)
  const end = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  return { start, end }
}

const getLastNDays = (days: number): { start: Date; end: Date } => {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - days)
  return { start, end }
}

const isQuickActionActive = (action: string): boolean => {
  if (!startDate.value || !endDate.value) return false

  const today = getToday()
  const yesterday = getYesterday()
  const todayStr = formatDate(today)
  const yesterdayStr = formatDate(yesterday)

  switch (action) {
    case 'today':
      return startDate.value === todayStr && endDate.value === todayStr
    case 'yesterday':
      return startDate.value === yesterdayStr && endDate.value === yesterdayStr
    case 'thisWeek': {
      const { start, end } = getThisWeek()
      return startDate.value === formatDate(start) && endDate.value === formatDate(end)
    }
    case 'thisMonth': {
      const { start, end } = getThisMonth()
      return startDate.value === formatDate(start) && endDate.value === formatDate(end)
    }
    case 'last7Days': {
      const { start, end } = getLastNDays(6)
      return startDate.value === formatDate(start) && endDate.value === formatDate(end)
    }
    case 'last30Days': {
      const { start, end } = getLastNDays(29)
      return startDate.value === formatDate(start) && endDate.value === formatDate(end)
    }
    default:
      return false
  }
}

const applyQuickAction = (action: string): void => {
  switch (action) {
    case 'today': {
      const today = getToday()
      startDate.value = formatDate(today)
      endDate.value = formatDate(today)
      break
    }
    case 'yesterday': {
      const yesterday = getYesterday()
      startDate.value = formatDate(yesterday)
      endDate.value = formatDate(yesterday)
      break
    }
    case 'thisWeek': {
      const { start, end } = getThisWeek()
      startDate.value = formatDate(start)
      endDate.value = formatDate(end)
      break
    }
    case 'thisMonth': {
      const { start, end } = getThisMonth()
      startDate.value = formatDate(start)
      endDate.value = formatDate(end)
      break
    }
    case 'last7Days': {
      const { start, end } = getLastNDays(6)
      startDate.value = formatDate(start)
      endDate.value = formatDate(end)
      break
    }
    case 'last30Days': {
      const { start, end } = getLastNDays(29)
      startDate.value = formatDate(start)
      endDate.value = formatDate(end)
      break
    }
  }
  handleDateChange()
}

const handleDateChange = (): void => {
  validateDates()
}

const validateDates = (): void => {
  if (startDate.value && endDate.value) {
    const start = new Date(startDate.value)
    const end = new Date(endDate.value)
    if (start > end) {
      endDate.value = startDate.value
    }
  }
}

const applyDates = (): void => {
  let result = null
  if (startDate.value && endDate.value) {
    result = {
      startDate: startDate.value,
      endDate: endDate.value
    }
  }
  emit('update:modelValue', result)
  emit('change', result)
  closeDropdown()
}

const clearDates = (): void => {
  startDate.value = ''
  endDate.value = ''
  emit('update:modelValue', null)
  emit('change', null)
  closeDropdown()
}

const toggleDropdown = (): void => {
  isOpen.value = !isOpen.value
}

const closeDropdown = (): void => {
  isOpen.value = false
}

// 点击外部关闭下拉框
const handleOutsideClick = (event: MouseEvent): void => {
  const target = event.target as HTMLElement
  const picker = document.querySelector('.date-picker') as HTMLElement
  if (picker && !picker.contains(target)) {
    closeDropdown()
  }
}

onMounted(() => {
  document.addEventListener('click', handleOutsideClick)
})

onUnmounted(() => {
  document.removeEventListener('click', handleOutsideClick)
})
</script>

<style scoped>
.date-picker {
  position: relative;
  width: 240px;
}

.picker-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  height: 36px;
  background-color: var(--theme-bg-secondary);
  border: 1px solid var(--theme-border-light);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.picker-trigger:hover {
  border-color: var(--theme-primary);
}

.selected-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trigger-icon {
  color: var(--theme-text-secondary);
}

.selected-text {
  color: var(--theme-text-primary);
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chevron {
  color: var(--theme-text-secondary);
  transition: transform 0.2s ease;
}

.chevron.rotated {
  transform: rotate(180deg);
}

.dropdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: transparent;
  z-index: 998;
}

.dropdown-content {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  width: 100%;
  background-color: var(--theme-bg-primary);
  border: 1px solid var(--theme-border-light);
  border-radius: 6px;
  box-shadow: var(--theme-shadow);
  z-index: 999;
  padding: 12px;
}

.date-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.date-input-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.date-label {
  font-size: 12px;
  color: var(--theme-text-secondary);
}

.date-input {
  height: 32px;
  padding: 0 8px;
  border: 1px solid var(--theme-border-light);
  border-radius: 4px;
  font-size: 14px;
  color: var(--theme-text-primary);
  background-color: var(--theme-bg-secondary);
}

.date-input:focus {
  border-color: var(--theme-primary);
  outline: none;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 12px;
}

.quick-action-btn {
  padding: 6px 0;
  font-size: 12px;
  color: var(--theme-text-secondary);
  background-color: var(--theme-bg-tertiary);
  border: 1px solid var(--theme-border-light);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.quick-action-btn:hover {
  border-color: var(--theme-primary);
}

.quick-action-btn.active {
  color: var(--theme-primary);
  border-color: var(--theme-primary);
  background-color: var(--theme-primary-light);
}

.date-actions {
  display: flex;
  gap: 8px;
}

.clear-btn,
.apply-btn {
  flex: 1;
  height: 32px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-btn {
  color: var(--theme-text-secondary);
  background-color: var(--theme-bg-secondary);
  border: 1px solid var(--theme-border-light);
}

.clear-btn:hover {
  border-color: var(--theme-text-secondary);
}

.apply-btn {
  color: white;
  background-color: var(--theme-primary);
  border: 1px solid var(--theme-primary);
}

.apply-btn:hover {
  background-color: var(--theme-primary-hover);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .date-picker {
    width: 100%;
  }
}
</style>
